<template>
    <div>
<!-- 面包屑导航条位置 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
<!-- 卡片内容区域 -->
        <el-card class="box-card" > 
            <el-row >
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <el-table  border stripe :data="rolesList">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdbottom','vcenter', i1 === 0 ? 'bdtop' : '']">
                            <!-- 渲染一级权限的区域 -->
                            <el-col :span="5"> 
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级权限的区域 -->
                            <el-col :span="19">
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 ===0 ? '' : 'bdtop','vcenter']">
                                    <el-col :span="6">
                                        <el-tag @close="removeRightById(scope.row,item2.id)" closable type="success" >{{item2.authName}}</el-tag>
                                         <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">                                        
                                        <el-tag @close="removeRightById(scope.row,item3.id)" closable type="warning" v-for="(item3) in item2.children" :key="item3.id" >{{item3.authName}}</el-tag>         
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>      
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" ></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                     <!-- 通过作用域插槽来定义 slot-scope="scope" -->
                    <template slot-scope="scope">
                        <el-button type="primary"  size="mini" icon="el-icon-edit" @click="modifyRole(scope.row.id)">编辑</el-button>
                        <el-button type="success"  size="mini" icon="el-icon-delete" @click="roleDelete(scope.row.id)">删除</el-button>
                        <el-button type="warning"  size="mini" icon="el-icon-setting" @click="showAssignRole(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>   
            </el-table>

            <!-- 添加角色弹框 -->
            <el-dialog
            title="添加新角色"
            :visible.sync="addDialogVisible"
            width="50%" @close="addDialogClosed"           
            >
            <!-- 文本主题区域 -->
            <el-form :model="addRolesForm" status-icon :rules="addRolesRules" ref="addRolesRef" >
            
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input type="text" v-model="addRolesForm.roleName" autocomplete="off"></el-input>
                    </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input type="text" v-model="addRolesForm.roleDesc" autocomplete="off"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 修改信息弹出面板 -->
             <el-dialog
            title="修改用户信息"
            :visible.sync="modifyDialogVisible"
            width="50%"
            @close="modifyDialogClosed"           
            >
            <!-- 文本主题区域 -->
            <el-form :model="modifyRoleForm" status-icon :rules="modifyRolesRules" ref="modifyRolesRef"  >
            <el-form-item label="角色名称" prop="roleName" >
                <el-input type="text"  v-model="modifyRoleForm.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input type="text" v-model="modifyRoleForm.roleDesc" autocomplete="off"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="modifyDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="modifyRoleInfo">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 分配权限弹框 -->
             <el-dialog
            title="分配权限"
            :visible.sync="assignDialogVisible"
            width="50%"
            @close="resetAssign"         
            >
            <!-- 文本主题区域 -->
            <el-tree
            :data="rightsList"
            show-checkbox
            node-key="id" 
            default-expand-all
            ref="treeRef"
            :default-checked-keys="defaulKeys"
            :props="defaultProps">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="assignDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
            </el-dialog>



        </el-card>





    </div>
</template>

<script>
export default {
    data() {
        return {
            //树形控件数据设置
            defaultProps: {
                children: 'children',
                label: 'authName'
            },
            addDialogVisible: false,
            modifyDialogVisible: false,
            assignDialogVisible: false,
            roleId:'',
            //权限列表信息
            rightsList: [],
            //角色列表信息
            rolesList: [],
            //修改用户的信息
            modifyRoleForm: {},
            //默认选中树形的数组值
            defaulKeys: [],
            //添加用户的信息
            addRolesForm:{
                roleName: '',
                roleDesc: ''
            },
            //添加用户的规则
            addRolesRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: false, message: '请输入角色描述', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],
            },
            //修改用户的规则
            modifyRolesRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],
            }
        }
    },
    created () {
        this.getRolesList()
    },
    methods: {
        //获取角色列表信息
        async getRolesList () {
            const {data: res} = await this.$http.get('roles')
            if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
            this.rolesList = res.data
            console.data
        },
        //监听清空表单数据
        //resetFields()清空表单事件
        addDialogClosed () {
            this.$refs.addRolesRef.resetFields()
        },
        modifyDialogClosed () {
            this.$refs.modifyRolesRef.resetFields()
        },

        //添加角色
        addRoles () {
            //先验证信息是否合法
            this.$refs.addRolesRef.validate(async valid =>{
                if(!valid) return 

            //合法则发起添加角色请求
            const {data: res} = await this.$http.post('roles',this.addRolesForm)
           
            if(res.meta.status !== 201 ) return this.$message.error('添加角色失败')
            //添加成功后重新从数据库获取数据
            this.getRolesList()
            this.addDialogVisible = false
            })
        },
        //根据id修改角色,先查询到角色，并将数据获取到弹出文本框中，分为两步
        async modifyRole (id) {
            this.modifyDialogVisible = true
            const {data: res} = await this.$http.get('roles/'+ id,)
            if(res.meta.status !== 200) return this.$message.error('修改信息失败')
            
            //存放要修改的数据的面板
            this.modifyRoleForm = res.data
        },
        //第二部，提交修改后的信息,id在获取到的modifyRolesForm中
        async modifyRoleInfo () {
            const {data: res} = await this.$http.put('roles/' + this.modifyRoleForm.roleId + '',{
                roleName: this.modifyRoleForm.roleName,
                roleDesc: this.modifyRoleForm.roleDesc
            })
            if(res.meta.status !==200) return this.$message.error('修改角色信息失败')

            this.$message.success('修改角色信息成功')
            this.getRolesList()
            this.modifyDialogVisible = false

        },

        //根据id删除角色
        async roleDelete (id) {
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)//.catch()捕获错误信息并返回

            if(confirmResult !== 'confirm'){
                return this.$message.info('已经取消了删除')
            }
            //确定删除操作
            const {data: res} = await this.$http.delete('roles/'+ id)   
            if(res.meta.status !== 200) return this.$message.error('删除角色失败') 
            this.$message.success('成功删除角色')
            this.getRolesList()
        },
        //根据id删除权限
        async removeRightById (role,id) {
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if(confirmResult !== 'confirm') return this.$message.info('已经取消了删除操作')

            const {data: res} = await this.$http.delete('roles/' + role.id+'/rights/'+id)
            if(res.meta.status !== 200) return this.$message.error('删除失败')
            this.$message.success('成功删除权限')
            //重新为渲染的单个页面值赋值，防止关闭页面重新整体赋值
            role.children = res.data
            // this.getRolesList()
        },
        
        //显示分配权限页面
        async showAssignRole (role) {
            this.roleId = role.id
            //在显示页面前先获取数据渲染到页面
            const {data: res} = await this.$http.get('rights/tree')
            if(res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.rightsList = res.data
            this.assignDialogVisible = true

            this.getDefaultKeys(role,this.defaulKeys)
        },
        //定义一个递归函数，获取到3级权限的id，将其放入数组中
        getDefaultKeys (node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item => this.getDefaultKeys(item,arr));
        },
        //关闭权限面板清空旧的默认数据数组
        resetAssign () {
            this.defaulKeys = []
        },
        //点击确定提交选中的状态数据
        async allotRights () {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')

          const {data: res} = await this.$http.post( `roles/${this.roleId}/rights`, {rids: idStr} )
          if(res.meta.status !== 200){
              return this.$message.error('分配权限失败')
          }

          this.$message.success('分配权限成功')
          this.getRolesList()
          this.assignDialogVisible = false
        }
    },
};
</script>

<style scoped lang="scss">
.el-tag{
    margin: 7px;
}
.bdtop {
    border-top: 1px solid #eee;
}
.bdbottom {
    border-bottom: 1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>
